package com.appbee.core.client.cell;

import com.appbee.core.client.templates.CommonTemplates;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;

/**
 * Cell with edit and delete button in editMode.
 * 
 * @author jakobmarrunarsson
 * 
 * @param <T>
 */
public abstract class EditableCell<T> extends AbstractCell<T>
{
	private boolean editMode = false;
	private final CommonTemplates html;
	private final EditableCellStyle style;
	private final ICellEditListener<T> listener;

	private static CellConstants CONSTANTS;

	public EditableCell(boolean editMode, CommonTemplates html,
						EditableCellStyle style,
			ICellEditListener<T> listener)
	{
		super("click");
		this.editMode = editMode;
		this.html = html;
		this.style = style;
		this.listener = listener;
		if (CONSTANTS == null)
			CONSTANTS = GWT.create(CellConstants.class);
	}

	@Override
	public void render(com.google.gwt.cell.client.Cell.Context context,
			T value, SafeHtmlBuilder sb)
	{
		if (editMode)
		{
			SafeHtmlBuilder bar = new SafeHtmlBuilder();
			bar.append(html.button(	style.cellEditButton(),
									"edit",
									CONSTANTS.edit(),
									CONSTANTS.edit()));
			bar.append(html.button(	style.cellDeleteButton(),
									"delete",
									CONSTANTS.delete(),
									CONSTANTS.delete()));
			sb.append(html.div(style.cellEditButtons(), bar.toSafeHtml()));
		}
	}

	@Override
	public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context,
			Element parent, T value, NativeEvent event,
			ValueUpdater<T> valueUpdater)
	{
		if (listener != null)
		{
			String type = event.getType();
			Element target = event.getEventTarget().cast();
			if ("click".equals(type) && "BUTTON".equals(target.getTagName()))
			{
				if ("delete".equals(target.getAttribute("name")))
				{
					listener.onDelete(value);
				}
				else
				{
					listener.onEdit(context, parent, value, event);
				}
			}
		}
		super.onBrowserEvent(context, parent, value, event, valueUpdater);

	}

}
